package org.unidbfw.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import org.unidbfw.common.UniDBFWException;
import org.unidbfw.model.IModelManager;
import org.unidbfw.model.ModelManager;

import oracle.jdbc.driver.OracleDriver;

public class ConnectionHelper
{

	private static Connection connection;
	/*
	 * connectionSettings[0] - db_url
	 * connectionSettings[1] - db_login
	 * connectionSettings[2] - db_password
	 */
	private static final String[] connectionSettings = new String[3];
	
	
	public static Connection getConnection() throws UniDBFWException
	{
		System.out.println("ConnectionHelper.getConnection()");
		if (connection == null)
		{
			try
			{
				loadConnectionSettings();
				DriverManager.registerDriver(new OracleDriver());
				connection = DriverManager.getConnection(connectionSettings[0], connectionSettings[1], connectionSettings[2]);
			}
			catch (SQLException e)
			{
				throw new UniDBFWException(e.getMessage(), e);
			}
		}
		return connection;
	}
	
	public static void closeConnection() throws UniDBFWException
	{
		System.out.println("ConnectionHelper.closeConnection()");
		try
		{
			connection.close();
		}
		catch (SQLException e)
		{
			throw new UniDBFWException(e.getMessage(), e);
		}
	}
	
	public static void closeStatement(Statement statement) throws UniDBFWException
	{
		System.out.println("ConnectionHelper.closeStatement()");
		try
		{
			statement.close();
		}
		catch (SQLException e)
		{
			throw new UniDBFWException(e.getMessage(), e);
		}
	}
	
	private static void loadConnectionSettings() throws UniDBFWException
	{
		System.out.println("ConnectionHelper.loadConnectionSettings()");
		IModelManager man = ModelManager.getInst();
		connectionSettings[0] = man.getDbUrl();
		connectionSettings[1] = man.getDbLogin();
		connectionSettings[2] = man.getDbPassword();
	}
	
}
